import Taro from '@tarojs/taro'
import request from '@/utils/request/doRequest'
import authority from '@/utils/authority'
import { redirectLogin } from '@/utils/router'

import { isWx } from '../validate'

// code 换取 session_key
async function fetchSessionKey(code) {
  const {
    session_key,
    unionid,
    token,
    openid = '',
    user = {},
    visitor = {}
  } = await request({
    url: '/api/app/v1/miniapp/session',
    method: 'post',
    data: { code }
  })
  user.session_key = session_key
  user.unionid = unionid
  user.openid = openid
  user.visitor = visitor
  authority.set(user)
  if (token) {
    user.token = token
    authority.set(user)
    return user
  }

  return redirectLogin()
}

export default () => {
  return new Promise((resolve, reject) => {
    const user = authority.get() || {}
    if (user.token) return resolve(user) // todo
    if (!isWx) {
      return redirectLogin()
    }
    const errorHandle = e => {
      console.error(e)
      Taro.showToast({
        title: e.message || '登录失败',
        icon: 'none'
      })
      reject(e)
    }
    Taro.login({
      success({ code }) {
        fetchSessionKey(code)
          .then(resolve)
          .catch(errorHandle)
      },
      fail(e) {
        errorHandle(e)
      }
    })
  })
}
